import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login.vue'
import Register from '../views/register.vue'
import store from '@/store' // 引入store对象

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: "/login"
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/register',
    name: 'register',
    component: Register
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/home.vue'),
  },
  {
    path: '/screenData',
    name: 'screenData',
    component: () => import('@/views/mains/screenData.vue'),
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('@/views/user/user.vue'),
  },
  {
    path: '/a',
    name: 'a',
    component: () => import('@/views/a.vue'),
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register']

router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    if (!store.state.userInfo.username) {
      // 调用actions里方法请求数据
      store.dispatch('initUserInfo')
      next()
    } else {
      store.dispatch('initUserInfo')
      next()
    }
  } else {
    // 如果无token
    // 如果去的是白名单页面, 则放行
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 如果其他页面请强制拦截并跳转到登录页面
      next('/login')
    }
  }
})
export default router
